  Ext.namespace("avatar.component");  
  
 	//DWR exception handle
	dwr.engine.setErrorHandler(function(msg, ex){
		 //Session timedout/invalidated  	 
	     if(ex && ex.javaClassName  
	              == 'cc.avatar.model.BusinessException'){      	
		    Ext.MessageBox.show({
	           title: '错误',
	           msg: ex.message,
	           icon: Ext.MessageBox.ERROR,
	           buttons: Ext.MessageBox.OK        
	       });
	     }
	}); 
  
if(Ext.LoadMask){
  Ext.LoadMask.prototype.msg = "载入中...";
}

Ext.app.SearchField = Ext.extend(Ext.form.TwinTriggerField, {
    initComponent : function(){
        if(!this.store.baseParams){
			this.store.baseParams = {};
		}
		Ext.app.SearchField.superclass.initComponent.call(this);
		this.on('specialkey', function(f, e){
            if(e.getKey() == e.ENTER){
                this.onTrigger2Click();
            }
        }, this);
    },

    validationEvent:false,
    validateOnBlur:false,
    trigger1Class:'x-form-clear-trigger',
    trigger2Class:'x-form-search-trigger',
    hideTrigger1:true,
    width:180,
    hasSearch : false,
    paramName : 'query',

    onTrigger1Click : function(){
        if(this.hasSearch){
            this.store.baseParams[this.paramName] = '';
			this.store.removeAll();
			this.el.dom.value = '';
            this.triggers[0].hide();
            this.hasSearch = false;
			this.focus();
        }
    },

    onTrigger2Click : function(){
        var v = this.getRawValue();
        if(v.length < 1){
            this.onTrigger1Click();
            return;
        }
		if(v.length < 2){
			Ext.Msg.alert('Invalid Search', 'You must enter a minimum of 2 characters to search the API');
			return;
		}
		this.store.baseParams[this.paramName] = v;
        var o = {start: 0};
        this.store.reload({params:o});
        this.hasSearch = true;
        this.triggers[0].show();
		this.focus();
    }
});
/**
 * Makes a ComboBox more closely mimic an HTML SELECT.  Supports clicking and dragging
 * through the list, with item selection occurring when the mouse button is released.
 * When used will automatically set {@link #editable} to false and call {@link Ext.Element#unselectable}
 * on inner elements.  Re-enabling editable after calling this will NOT work.
 *
 * @author Corey Gilmore
 * http://extjs.com/forum/showthread.php?t=6392
 *
 * @history 2007-07-08 jvs
 * Slight mods for Ext 2.0
 */
Ext.ux.SelectBox = function(config){
	this.searchResetDelay = 1000;
	config = config || {};
	config = Ext.apply(config || {}, {
		editable: false,
		forceSelection: true,
		rowHeight: false,
		lastSearchTerm: false,
        triggerAction: 'all',
        mode: 'local'
    });

	Ext.ux.SelectBox.superclass.constructor.apply(this, arguments);

	this.lastSelectedIndex = this.selectedIndex || 0;
};

Ext.extend(Ext.ux.SelectBox, Ext.form.ComboBox, {
    lazyInit: false,
	initEvents : function(){
		Ext.ux.SelectBox.superclass.initEvents.apply(this, arguments);
		// you need to use keypress to capture upper/lower case and shift+key, but it doesn't work in IE
		this.el.on('keydown', this.keySearch, this, true);
		this.cshTask = new Ext.util.DelayedTask(this.clearSearchHistory, this);
	},

	keySearch : function(e, target, options) {
		var raw = e.getKey();
		var key = String.fromCharCode(raw);
		var startIndex = 0;

		if( !this.store.getCount() ) {
			return;
		}

		switch(raw) {
			case Ext.EventObject.HOME:
				e.stopEvent();
				this.selectFirst();
				return;

			case Ext.EventObject.END:
				e.stopEvent();
				this.selectLast();
				return;

			case Ext.EventObject.PAGEDOWN:
				this.selectNextPage();
				e.stopEvent();
				return;

			case Ext.EventObject.PAGEUP:
				this.selectPrevPage();
				e.stopEvent();
				return;
		}

		// skip special keys other than the shift key
		if( (e.hasModifier() && !e.shiftKey) || e.isNavKeyPress() || e.isSpecialKey() ) {
			return;
		}
		if( this.lastSearchTerm == key ) {
			startIndex = this.lastSelectedIndex;
		}
		this.search(this.displayField, key, startIndex);
		this.cshTask.delay(this.searchResetDelay);
	},

	onRender : function(ct, position) {
		this.store.on('load', this.calcRowsPerPage, this);
		Ext.ux.SelectBox.superclass.onRender.apply(this, arguments);
		if( this.mode == 'local' ) {
			this.calcRowsPerPage();
		}
	},

	onSelect : function(record, index, skipCollapse){
		if(this.fireEvent('beforeselect', this, record, index) !== false){
			this.setValue(record.data[this.valueField || this.displayField]);
			if( !skipCollapse ) {
				this.collapse();
			}
			this.lastSelectedIndex = index + 1;
			this.fireEvent('select', this, record, index);
		}
	},

	render : function(ct) {
		Ext.ux.SelectBox.superclass.render.apply(this, arguments);
		if( Ext.isSafari ) {
			this.el.swallowEvent('mousedown', true);
		}
		this.el.unselectable();
		this.innerList.unselectable();
		this.trigger.unselectable();
		this.innerList.on('mouseup', function(e, target, options) {
			if( target.id && target.id == this.innerList.id ) {
				return;
			}
			this.onViewClick();
		}, this);

		this.innerList.on('mouseover', function(e, target, options) {
			if( target.id && target.id == this.innerList.id ) {
				return;
			}
			this.lastSelectedIndex = this.view.getSelectedIndexes()[0] + 1;
			this.cshTask.delay(this.searchResetDelay);
		}, this);

		this.trigger.un('click', this.onTriggerClick, this);
		this.trigger.on('mousedown', function(e, target, options) {
			e.preventDefault();
			this.onTriggerClick();
		}, this);

		this.on('collapse', function(e, target, options) {
			Ext.getDoc().un('mouseup', this.collapseIf, this);
		}, this, true);

		this.on('expand', function(e, target, options) {
			Ext.getDoc().on('mouseup', this.collapseIf, this);
		}, this, true);
	},

	clearSearchHistory : function() {
		this.lastSelectedIndex = 0;
		this.lastSearchTerm = false;
	},

	selectFirst : function() {
		this.focusAndSelect(this.store.data.first());
	},

	selectLast : function() {
		this.focusAndSelect(this.store.data.last());
	},

	selectPrevPage : function() {
		if( !this.rowHeight ) {
			return;
		}
		var index = Math.max(this.selectedIndex-this.rowsPerPage, 0);
		this.focusAndSelect(this.store.getAt(index));
	},

	selectNextPage : function() {
		if( !this.rowHeight ) {
			return;
		}
		var index = Math.min(this.selectedIndex+this.rowsPerPage, this.store.getCount() - 1);
		this.focusAndSelect(this.store.getAt(index));
	},

	search : function(field, value, startIndex) {
		field = field || this.displayField;
		this.lastSearchTerm = value;
		var index = this.store.find.apply(this.store, arguments);
		if( index !== -1 ) {
			this.focusAndSelect(index);
		}
	},

	focusAndSelect : function(record) {
		var index = typeof record === 'number' ? record : this.store.indexOf(record);
		this.select(index, this.isExpanded());
		this.onSelect(this.store.getAt(record), index, this.isExpanded());
	},

	calcRowsPerPage : function() {
		if( this.store.getCount() ) {
			this.rowHeight = Ext.fly(this.view.getNode(0)).getHeight();
			this.rowsPerPage = this.maxHeight / this.rowHeight;
		} else {
			this.rowHeight = false;
		}
	}

});

  //Sales main panel
   avatar.salesPanel = Ext.extend(Ext.grid.EditorGridPanel, {
	    query: null,
	    saleId: null,
	    //selectedSaleState: null,
        columns : [ 
            new Ext.grid.RowNumberer({hidden:true}),			
			{header : '产品', dataIndex : 'product.name',  width : 120, summaryType: 'count', 
			  summaryRenderer: function(v, params, data){
                    return '(' + v +' 项)';
                }},
            {header : '计划块数', dataIndex : 'contractAmount',  width : 65, summaryType: 'sum'},   
			{header : '已运块数', dataIndex : 'amount',  width : 60, summaryType: 'sum'},
			{header : '价格', dataIndex : 'price', width : 60},
			{header : '金额', dataIndex : 'sum', width : 60, summaryType: 'sum'},
			{header : 'tn', dataIndex : 'sale.id', hidden: true}
		 ],
         initComponent: function() { 
			 var me = this;
			 this.cm = new Ext.grid.ColumnModel({
					columns: this.columns
			 });

			 this.store = new Ext.data.GroupingStore({
					sortInfo: {field: 'sale.id', direction: 'ASC'},
					groupField: 'sale.id',
					remoteSort : true,
				    data: [],
					reader: new Ext.data.JsonReader({
						idProperty: 'id',
					    fields: [
						   {name: 'saleSummary', type:'string'},						   
						   {name: 'product.name', type:'string'},
						   {name: 'amount', type:'int'},
						   {name: 'price', type:'int'},
						   {name: 'contractAmount', type:'int'},
						   {name: 'sum', type:'int'},
						   {name: 'id', type:'int'},
						   {name: 'sale.id', type:'int'},
						   {name: 'sale.state', type: 'string'}
					  ]})
			}); 
			//货运单
			this.carriage_ds = new Ext.data.GroupingStore({
					sortInfo: {field: 'id', direction: 'ASC'},
					//groupOnSort: true,
					groupField: 'summary',
				    data: [],
					reader: new Ext.data.JsonReader({
						idProperty: 'id',
					    fields: [
					       {name: 'summary', type: 'string'},
						   {name: 'location.name', type:'string'},						   
						   {name: 'product.name', type:'string'},
						   {name: 'amount', type:'int'},
						   {name: 'id', type:'int'}
					  ]})
			 });
 			
			 this.carriage_view = new Ext.grid.GroupingView({
				forceFit:true,
				showGroupName: false,
				enableNoGroups:false,
				enableGroupingMenu:false,
				hideGroupedColumn: true,
				startCollapsed:true //默认不展开
			 });
			 
			  // define a custom summary function
		    //Ext.ux.grid.GroupSummary.Calculations['totalCost'] = function(v, record, field){
		    //    return v + (record.data.estimate * record.data.rate);
		    //};

			// utilize custom extension for Group Summary
		    this.plugins = new Ext.ux.grid.GroupSummary();


			 
			 this.view = new Ext.grid.GroupingView({
				forceFit:true,
				showGroupName: false,
				enableNoGroups:false,
				enableGroupingMenu:false,
				hideGroupedColumn: true,
				startCollapsed:true, //默认不展开
				groupTextTpl: '{[values.rs[0].get("saleSummary")]}',
			    toggleGroup : function(group, expanded){
			    	//if (expanded != undefined) return;
			        var gel = Ext.get(group);
			        expanded = Ext.isDefined(expanded) ? expanded : gel.hasClass('x-grid-group-collapsed');

			        if(this.state[gel.id] !== expanded){		        	
			            this.grid.stopEditing(true);
			            
			            //only expand current group, and close other groups
				    	if (expanded){
				    		var start = group.id.indexOf('sale.id-');                          
				    		//remember expanded sale tracking number
				    		me.saleId = group.id.substring(start + 8);
				    		this.collapseAllGroups();
				    		//cache group
				    		me.group = group;

				    	}
			            this.state[gel.id] = expanded;
			            gel[expanded ? 'removeClass' : 'addClass']('x-grid-group-collapsed');

			        } 
			    }
			}); 
           
            this.sm = new Ext.grid.RowSelectionModel({singleSelect:true});

          	this.refresh();	

          	var sale_item_sm = new Ext.grid.RowSelectionModel({singleSelect:true});
			    
			sale_item_sm.on('selectionchange', function(sm){	
		        var record = sm.getSelected();
		        var btn = Ext.getCmp('remove-sale-item-btn');	
		        //if (record)
		        //  alert(!record || record.get('amount') != 0);
		        btn.setDisabled(!record || record.get('amount') != 0);
		        //alert(!record || record.get('amount') != 0);
			});    
			
			 this.tbar = 
				 [  new Ext.Toolbar.Button({ id: 'sale-add-btn', name: 'add', text:'新建登记单', handler : function(){ me.add(); } }),
				    {text:'打印', handler: function(){
				       printGrid(me,'销售单', '', '');
				    }},	
				  {
				      text:'货运与支付', handler: function(){                       
                         if (me.saleId == null){
                         	alert('请先选择一个销售单');
                         	return;
                         }

                        var location_ds = new Ext.data.JsonStore({
							fields: [ 'id', 'name' ]
						}),
						carrier_ds = new Ext.data.JsonStore({
			                fields: [ 'id', 'name' ]
						}), 
						payer_ds = new Ext.data.JsonStore({
			                fields: [ 'id', 'name', 'phoneNumber' ]
						}), 
					    product_ds = new Ext.data.JsonStore({
							fields: [ 'id', 'name' ]
						}),
						sale_items_ds = new Ext.data.JsonStore({
							fields: ['id', 'product.id', 'product.name', 'amount','contractAmount', 'price']							
						});
						
						sale_items_ds.on('update', function(){
						    Ext.getCmp('save-price-btn').enable();							
						});
							   
						ProductManager.getAllProduct(function(data){ product_ds.loadData(data); });
						ProductManager.getAllLocation(function(data){ location_ds.loadData(data); });
						PartyManager.getAllActivePartyByRole('carrier', function(data){ carrier_ds.loadData(data); });
						
						PartyManager.getAllActivePartyByRole('payer', function(data){ payer_ds.loadData(data); });

						var currentSale, state = '', cust, state_label = '完成';
		
						dwr.engine.setAsync(false);
						SaleManager.getCarriageItemsBySaleId(me.saleId, 
						  function(data){ me.carriage_ds.loadData(data);});
						
						SaleManager.getSaleById(me.saleId, function(data){
							currentSale = data;
						    state = data.state;
						    cust = data.customer;
						    sale_items_ds.loadData(data.items);
					    });
				        dwr.engine.setAsync(true);
						
				        if (state == 'in_transit')
				            state_label = '运送中';
				        else if(state == 'prepare_for_payment')
				            state_label = '待支付';

						var carriage_win = new Ext.Window({
							calculatePay : function(reload){
								if (reload){
									dwr.engine.setAsync(false);
									SaleManager.getSaleById(currentSale.id, function(data){
							            currentSale = data;
							            state = data.state;
							            if (state == 'in_transit')
								            state_label = '运送中';
								        else if(state == 'prepare_for_payment')
								            state_label = '待支付';
								        else
								            state_label = '完成';
								        sale_items_ds.loadData(data.items);
									});
									dwr.engine.setAsync(true);								
								}
								var allowEdit = (state == 'in_transit' || state == 'draft');
								Ext.getCmp('price-editor').getColumnModel().setEditable(1, allowEdit );
								Ext.getCmp('price-editor').getColumnModel().setEditable(3, allowEdit );
								
								var rp = currentSale.receivablePayment,
								  ep = currentSale.effectivePayment;
								if (currentSale.state == 'draft')
								   this.setTitle( currentSale.summary);
								else  
								   this.setTitle( currentSale.trackingNumber + ' (' + currentSale.customer.name + ') '+ state_label + ' 总金额:' + rp + ' 已付:' + ep);
								Ext.getCmp('add-carriage-builder').setVisible(state == 'draft' || state == 'in_transit');
								Ext.getCmp('sale-add-btn').setDisabled( state != 'in_transit' && state != 'draft');
								Ext.getCmp('pay-btn').setDisabled(state == 'close' || state == 'draft');
								Ext.getCmp('add-sale-plan-item-btn').setDisabled(state == 'close' || state == 'prepare_for_payment');
								
							},
						    constrain : true,
							layout : 'form',
							width : 580,
							closeAction : 'close',
							autoHeight : true,
							resizable : false,
							shadow : true,
							modal : true,
							closable : false,
							border : false,
							y: 20,
							items:[{
							   xtype: 'tabpanel',
							   activeTab: 0,
					           autoWidth: true,
					           autoHeight: true,
			                   items:[
			                    
								{ xtype:'editorgrid',
								  id : 'price-editor',
								  title: '产品明细',
								  height: 295,
								  store:sale_items_ds,
								  enableHdMenu: false,
								  sm : sale_item_sm,
							      clicksToEdit:1,
						          columns : [ 
									{header : '产品', dataIndex : 'product.name',  width : 160,
									 renderer: function(val, metadata, rec){		        		
						        		if (rec.get('amount') >= rec.get('contractAmount')) 
						        		    return '<span style="color:red;">' + val + '</span>';
								        else
								            return val;
						        	 }
									},
									{header : '计划块数', dataIndex : 'contractAmount',  width : 60,
									 editable : state== 'draft' || state == 'in_transit', editor: new Ext.form.NumberField({ allowDecimals: false })									
									},
									{header : '已运块数', dataIndex : 'amount',  width : 60},
									{header : '价格', dataIndex : 'price', width : 60,
									 editable : state=='in_transit', editor: new Ext.form.NumberField({ allowDecimals: false })}
								  ],
								  tbar:[
								    {  text:'增加产品', id: 'add-sale-plan-item-btn',
								     
								       handler: function(){
								    	
								       var p_ds =  new Ext.data.JsonStore({
											fields : ["id", "name"]
										});
										ProductManager.getAllProduct( function(data){
											p_ds.loadData(data);
										});
								    	
								       var add_item_form =  new Ext.FormPanel({
						                labelWidth: 65, 
					            		frame: true,
										defaults: {anchor: '99%'},
										defaultType: 'textfield', 				
						        		items : [
						        		  {xtype:'combo', fieldLabel:'产品',
						        		     store : p_ds,
						        		     id: 'add-sale-item-product-combo',
									         forceSelection : true,
									         displayField: 'name',
									         valueField:'id',
											 editable:false,
											 typeAhead: true,
											 mode: 'local',
											 triggerAction: 'all',
											 selectOnFocus:true,
											 allowBlank: false		        		  
						        		  },
			        		              {xtype:'numberfield', id: 'add-sale-item-amount', fieldLabel:'计划块数', 			        		              
			        		                value : 1, allowNegative : false, allowBlank: false}],
			        		              buttons: [{text:'保存', handler: function(){
			        		                 var pass = add_item_form.getForm().isValid();
			        		                 if (pass){
			        		                 	var pid = Ext.getCmp('add-sale-item-product-combo').getValue(),
			        		                 	    pname = Ext.getCmp('add-sale-item-product-combo').getRawValue(),
			        		                 	    amount = Ext.getCmp('add-sale-item-amount').getValue();
			        		                 	var index = sale_items_ds.findExact('product.id', pid);
			        		                 	if (index >=0){
			        		                 		alert('该 产品已经存在于当前运输单明细中，请另选 。')
			        		                 		return;
			        		                 	}
			        		                 	SaleManager.addSaleItem(me.saleId, pid, amount, function(d){
			        		                 	   	SaleManager.getSaleById(me.saleId, function(data){
													    sale_items_ds.loadData(data.items);
													});
			        		                 	});
			        		                 	Ext.getCmp('add-carriage-builder').addProductAvaiable(pid, pname);
			        		                 	add_item_win.close();
			        		                 }    	
			        		              }}, {text:'关闭', handler: function(){add_item_win.close();}}]  
								       });

                                       var add_item_win =  new Ext.Window({
										    constrain : true,
											layout : 'fit',
											title: '增加产品',
											width : 300,
											closeAction : 'close',
											height : 135,
											resizable : false,
											shadow : true,
											modal : true,
											closable : true,
											border : false,
											animCollapse : true,
											items : [add_item_form]											
										}).show();	    	
								    	
								     }	
								    },
								    {text:'删除', id: 'remove-sale-item-btn', disabled: true, handler: function(){
								   	     var cell = sale_item_sm.getSelected();
								   	     if (cell){
								   	     	Ext.getCmp('price-editor').stopEditing();
								   	     	SaleManager.removeSaleItem(cell.get('id'), function(d){								   	     	    							   	     	    
								   	     	    Ext.getCmp('add-carriage-builder').removeProductAvaiable(cell.get('product.id'));
								   	     	    sale_items_ds.remove(cell);	
								   	     	}); 						   	     	
								   	     }							    	
								     }							    
								    },
								   	{text:'保存', id: 'save-price-btn', disabled: true, handler: function(){
								    	Ext.getCmp('price-editor').stopEditing();
									    var size = sale_items_ds.getCount();
									    dwr.engine.setAsync(false);
									    for (var i=0; i<size; i++){
									    	var rec = sale_items_ds.getAt(i),
									    	    price = rec.get('price');
									    	SaleManager.updateSaleItemPrice(rec.get('id'), rec.get('contractAmount'), price);
									    }
									    dwr.engine.setAsync(true);
									    this.disable();
									    carriage_win.calculatePay(true);
									    //me.refresh();
									    	
									}}
								  
								  
								  ]								 			
								},
								{ xtype: 'grid', 
								  border: 1,
								  title: '货运单',
								  width: 140,
								  store: me.carriage_ds,
								  height:295,
								  view: me.carriage_view,
								  enableHdMenu: false,
								  columns: [
								    {header : '', dataIndex : 'summary', hidden: true},
								    {header: '仓库位置', dataIndex : 'location.name',  width: 65},
								    {header: '产品', dataIndex : 'product.name', width : 90},
								    {header: '数量', dataIndex : 'amount', width : 58}]
								}
								
								]},
						
							new avatar.carriageBuilder({
							    id: 'add-carriage-builder', 
							    hidden:state != 'in_transit' && state != 'draft',
							    trackingNumber : currentSale.trackingNumber,
							    saleId: currentSale.id,
							    customer: cust
							    })
							],
							tbar: [
							    { id: 'sale-add-btn',  text:'新增货运单', disabled: state != 'in_transit',handler : function(){ 
							    	var cb = Ext.getCmp('add-carriage-builder');
							    	if (cb.isValid(true)){
							    		
							    		Ext.MessageBox.confirm('确定','你确定要保存该新货运单吗?(请先打印并核对细项确保无误)' ,function(btn){
                                          if(btn=="yes"){
									    		var carriage = cb.getCarriage();
									    		SaleManager.addCarriage(currentSale.id, carriage, function(){
									    		   carriage_win.calculatePay(true);
									    		   
									    		   SaleManager.getCarriageItemsBySaleId(currentSale.id,
								                         function(data){
								                         	me.carriage_ds.loadData(data); 	
                                                            //clear carriage builder
								                         	cb.clear();
								                         });	
								                           
								                         
									    		});
                                          }
							    		});
							    	}
							    	
							    } },	
								{text:'支付', id: 'pay-btn', disabled: state == 'close', handler: function(){
								    
									SaleManager.getSaleById(me.saleId, function(data){
			                            if (data.readyForPay){
			                            	var leftPayment = Math.round((currentSale.receivablePayment - currentSale.effectivePayment)*100)/100;
			                            	var pay_form = new Ext.form.FormPanel({
										     	autoWidth: true,
							            		labelWidth: 55, 
							            		layout:'form',
												frame:true, 
												defaultType: 'textfield', 				
								        		items : [		
								        		  { xtype:'combo', anchor: '96%', id: 'sale-payer-id', fieldLabel: '收款人',
								        		    store: payer_ds,
													forceSelection: true,
													displayField: 'name',
													valueField:'id',
													editable: false,
													typeAhead: true,
													mode: 'local',
													//value: ,
													triggerAction: 'all',
													selectOnFocus:true,
													allowBlank: false								        		  
								        		  },
								        		  {inputType: 'password', anchor: '96%', id:'sale-pay-password', fieldLabel : '密码'},
								        		  { xtype: 'numberfield', anchor: '96%', id:'sale-pay-money', fieldLabel : '支付金额', 
								        		    value: leftPayment, allowDecimals: false, minValue: 1, maxValue: leftPayment, allowBlank: false
								                  },
								                  { xtype: 'numberfield', anchor: '96%', id:'sale-commision-price', fieldLabel : '提成单价', 
								        		    allowDecimals: false, emptyText: '0', value: 0
								                  }, 
								                  { xtype: 'numberfield', anchor: '96%', id:'sale-freight-price', fieldLabel : '运输单价', 
								        		    allowDecimals: true, emptyText: '0', disabled: currentSale.customer.freightPrice > 0,
								        		    value : currentSale.customer.freightPrice
								                  }, 
								                  { xtype: 'label', html: '1.全款支付后销售单变为完成状态。<br/>2.提成单价仅在全款支付时需要。<br/>3.新客户的运输单价可以推迟到最终支付时设定。'}
        		  
								        		],
								        		buttons: [
								        		{text: '确定', handler: function() {
								        		    var cmp = Ext.getCmp('sale-pay-money');	
								        		    var payer = Ext.getCmp('sale-payer-id');
								        		    
								        		    if (cmp.isValid()&&payer.isValid()){
								        		    	var value = cmp.getValue(),
								        		    	    price = Ext.getCmp('sale-commision-price').getValue(),
								        		    	    freightPrice = Ext.getCmp('sale-freight-price').getValue(),
								        		    	    payPwd = Ext.getCmp('sale-pay-password').getValue();
								        		    	
								        		    	var index = payer_ds.findExact('id', payer.getValue()),
								        		    	    payerRec = payer_ds.getAt(index);
								        		    	
								        		    	if (payPwd != payerRec.get('phoneNumber')){
								        		    		alert('支付密码不正确！');
								        		    		return;
								        		    	}
								        		    	    
								        		    	if (price == '') price = 0;  
								        		    	if (freightPrice == '') freightPrice = 0;
								        		    	if (value == leftPayment){
								        		    		var msg = '全额支付余款, ';
								        		    		 msg += (price != '')?'销售提成单价为'+ price + ', ':
								        		    		                        '不计算销售提成, ';
								        		    		if (!Ext.getCmp('sale-freight-price').disabled)
								        		    		   msg += '运输单价为' + freightPrice + ', ';
								        		    		                        
								        		    		msg += "请确认。"
								        		    		Ext.MessageBox.confirm('确认', msg ,function(btn){
					                                          if(btn=="yes"){
					                                          	    
														    		SaleManager.payfull(currentSale.id, payer.getValue(), parseInt(price), parseFloat(freightPrice), function(){
														    		   currentSale.state = 'close';
														    		   carriage_win.calculatePay(true);
										                               pay_win.close();	
										                               
														    		});
					                                          }
												    		});
								        		    		
								        		    	} else {
								        		    		Ext.MessageBox.confirm('确认','支付金额为'+ value + ", 请确认。" ,function(btn){
					                                          if(btn=="yes"){						    		
														    		SaleManager.pay(currentSale.id, payer.getValue(), value, function(){
														    		   currentSale.state = 'prepare_for_payment';
														    		   carriage_win.calculatePay(true);
										                               pay_win.close();			                         
														    		});
					                                          }
												    		});
								        		    	}
								        		    }							        			
								        			
								        		} },
								        		{text: '取消', handler: function(){ pay_win.close();}}
								        		  
								        		]
								        		
								        		});
								        var pay_win = new Ext.Window({
										    constrain : true,
											layout : 'fit',
											width : 262,
											title: '付款',
											closeAction : 'close',
											height : 254,
											resizable : false,
											shadow : true,
											modal : true,
											closable : true,
											border : false,
										
											items:[pay_form]
										 });
							
										  pay_win.show();	     	
			                            } else 
			                                alert('请先完成定价。');
								    });
								}
								},
							    { text:'关闭', handler: function() { 							    							
									var cb = Ext.getCmp('add-carriage-builder');
							    	if (cb.isValid(false)){
							           Ext.MessageBox.confirm('确认','编辑中的运输单未保存，退出将丢失数据，确定要关闭窗口吗?' ,function(btn){
                                          if(btn=="yes"){
                                             carriage_win.close();
                                             me.refresh(); 
                                          }
								       });
							    	} else {
							    		carriage_win.close(); me.refresh(); 
							    	}
							    								    	
							      }
							    }
							
							
							]
						 });
			
						carriage_win.show(); 

						
						carriage_win.calculatePay(false);
				      }
				    }
				 ];
			 //call parent
             avatar.salesPanel.superclass.initComponent.apply(this);
			 
              

         },
         createForm : function(id,operation){// create editor window
         	    var me = this;
         	    var sale_item_editor = new Ext.ux.grid.RowEditor({
						saveText: '保存',
						cancelText: '取消'					
					}),
				item_ds = new Ext.data.JsonStore({
					fields : ["productId", "amount"]
				}),
				product_ds = new Ext.data.JsonStore({
					fields : ["id", "name"]
				});
				
				ProductManager.getAllProduct( function(data){
					product_ds.loadData(data);
				});
			    var form = new Ext.form.FormPanel({
			     	width: 450,
            		labelWidth: 75, 
            		layout:'form',
					frame:true, 
					defaultType: 'textfield', 				
	        		items : [	        		
    		   		  {  xtype:'fieldset',
	   					 title: '客户信息',	
	   					 defaults: {anchor: '99%'},
	   					 layout: 'form',
	   					 items:[
	   					    { xtype: 'trigger', id:'sale-customer-name',    					      
	   					      triggerClass : 'x-form-search-trigger', width: 375,
	   					      emptyText: '您可以输入拼音缩写并点击右侧放大镜图标，查询历史客户。',
	   					      fieldLabel : '客户名称', name : 'customerName', allowBlank: false,
	   					       onTriggerClick:function(){
	   					       	  var v = this.getValue(), self = this;
	   					       	  if (v == '') return;
	   					       	  var customer_ds = new Ext.data.JsonStore({
									fields: [ 'id', 'name', 'phoneNumber', 'freightPrice' ]
							      });
	   					       	  SaleManager.getCustomersByPinyin(v, function(data){
	   					       	      customer_ds.loadData(data);
	   					       	  });
								  var customerpicker = new Ext.Window({
								    constrain : true,
									layout : 'fit',
									width : 450,
									title: '选择客户 - 请双击选中的行',
									closeAction : 'close',
									height : 360,
									resizable : false,
									shadow : true,
									modal : true,
									closable : true,
									border : false,
									items:[
									  {
										xtype:'grid',
										border: false,
										//layout:'fit',
										enableHdMenu: false,
										store: customer_ds,
										columns: [
										   new Ext.grid.RowNumberer(),
										   {header: '客户名称', dataIndex : 'name', sortable:true, width: 240},
										   {header: '联系电话', dataIndex : 'phoneNumber', width : 110},
										   {header: '运输单价', dataIndex : 'freightPrice', width : 60}				
										],
										listeners: {
                                    	 'rowdblclick' : function(grid, rowIndex){
                                    		var rec = grid.store.getAt(rowIndex);
                                    		self.setValue(rec.get('name'));
                                    		Ext.getCmp('sale-customer-id').setValue(rec.get('id'));
                                    		Ext.getCmp('sale-customer-delivery-price').setValue(rec.get('freightPrice'));
                                    		Ext.getCmp('sale-customer-phonenumber').setValue(rec.get('phoneNumber'));
                                    		customerpicker.close();
                                    	}
                                       }
									  }

                                    ]
                                    
								  }).show();
	   					       	  
	   					       	  
	   					     } },
	        		        { xtype: 'numberfield', id:'sale-customer-delivery-price', fieldLabel : '运费单价', name : 'deliveryPrice', width:'95%', allowBlank: false, value: 0, minValue: 0},	   					 
   					        { xtype: 'textfield', id:'sale-customer-phonenumber', fieldLabel : '联系电话', name : 'customerPhoneNumber', width:'95%' }   					   
	   					 ]
    		   		  },
	        		  { xtype: 'hidden', id:'sale-customer-id', name : 'customerId'},
	        		 	        		  
	        		  {
						xtype : 'combo',
						fieldLabel: '销售员',
						id: 'sale-salesman-id',
						name : 'salesPerson',
						store: salesman_ds,
						forceSelection: true,
						displayField: 'name',
						valueField:'id',
						editable: false,
						typeAhead: true,
						mode: 'local',
						//value: '',
						triggerAction: 'all',
						selectOnFocus:true,
						width: 180,
						allowBlank: false
					  },
					  {
	        		  	xtype:'grid',
	        		  	id: 'new-sale-items-grid',
		                tbar: [
				           { id: 'sale-item-add-btn', text:'新建', handler : function(){ 				
								var newRec = new Ext.data.Record({productId: product_ds.getAt(0).get('id'), amount:0});
								sale_item_editor.stopEditing();	
								//var index  = item_ds.getCount() - 1;
								item_ds.insert(0, newRec);
								var grid = Ext.getCmp('new-sale-items-grid');
								grid.getView().refresh();
								
								grid.getSelectionModel().selectRow(0);
								sale_item_editor.startEditing(0);	 
						   } },
						   { id: 'sale-item-remove-btn', text:'删除', handler : function(){					      	 
						   	     var grid = Ext.getCmp('new-sale-items-grid');
						   	     var cell = grid.getSelectionModel().getSelected();
						   	     if (cell){
						   	     	sale_item_editor.stopEditing();
						   	     	item_ds.remove(cell);
						   	     }
						   	
						      }
						   }
						   	
						],
						plugins: [sale_item_editor],
	        		  	store: item_ds,
						sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
						columns:[
			               {
							   header: '产品',
							   dataIndex: 'productId',
							   sortable: true,
							   width: 180,
							   editor: {								
								 xtype: 'combo', 
							     store : product_ds,
						         forceSelection : true,
						         anchor:'-20',
						         displayField: 'name',
						         valueField:'id',
								 editable:false,
								 typeAhead: true,
								 mode: 'local',
								 triggerAction: 'all',
								 selectOnFocus:true,
								 allowBlank: false
							   },
							   renderer: function(val){
							   	   var index = product_ds.findExact('id', val);
							   	   if (index > -1)
							   	       return product_ds.getAt(index).get('name');
							   	   else 
							   	       return '';
							   }
							},
                            {
					            xtype: 'numbercolumn',
					            header: '块数',
					            dataIndex: 'amount',
					            width: 80,
					            format: '0',
					            editor: {
					                xtype: 'numberfield',
					                allowDecimals : false
					            }
					        } 
			                
			            ],
						autoWidth: true,
						height:250,
						frame:true,
						clicksToEdit:1			        		  	
	        		  }
					 // new avatar.carriageBuilder({id: 'carrage-builder', idprefix: '_'})
	        		  	        		
	        		],                   
	            	buttons : [
	            		{ text : '保存', handler: function(){    
	            		  // var cbuiler = Ext.getCmp('carrage-builder');
	            		   if (form.getForm().isValid() && item_ds.getCount()>0){
	            		   	  var sale = new SaleDto(),
            		   	        c = new Customer(),
            		   	        cid = Ext.getCmp('sale-customer-id').getValue(),
            		   	        salerId = Ext.getCmp('sale-salesman-id').getValue();
            		   	      if (cid != ''){
            		   	      	  c.id = cid;
            		   	      }
            		   	      c.name = Ext.getCmp('sale-customer-name').getValue();
            		   	      c.freightPrice = Ext.getCmp('sale-customer-delivery-price').getValue();
            		   	      c.phoneNumber = Ext.getCmp('sale-customer-phonenumber').getValue();
            		   	      
            		   	      sale.customer = c;
            		   	      sale.salerId = salerId;
                              
            		   	      var productIds = new Array(), amounts = new Array();

	                    	  for (i=0,cnt = item_ds.getCount() ;i<cnt;i+=1){
	                    		    var rec = item_ds.getAt(i);	
	                    		    productIds[i] = rec.get("productId"); 
	                    		    amounts[i] = rec.get("amount");
	                    	  }
	                    	  sale.productIds = productIds;
	                    	  sale.amounts = amounts
            		   	      
            		   	      SaleManager.addSale(sale, function(data){
            		   	         //refresh grid
            		   	      	me.refresh();
            		   	      	
            		   	      	editor.close();
            		   	      	alert('销售单创建成功。')
            		   	      });
	            		   }
	            			
	            			
	            		} },
	            	    { text : '取消', handler: function(){ editor.close();} }
	            	]
			});

			var editor = new Ext.Window({
			    constrain : true,
				layout : 'fit',
				width : 500,
				title: '销售单[草稿]',
				closeAction : 'close',
				height : 475,
				resizable : false,
				shadow : true,
				modal : true,
				closable : true,
				border : false,
				y: 30,
				items:[form]
			 });

			editor.show();
        },
        add: function(){//add action
			this.createForm()
		},
		edit: function(){//edit action
			var me = this;
			var cell = this.getSelectionModel().getSelected();
			cell && this.createForm(cell.id, 'edit');
		},
		remove: function(){//remove action
			
		},
		setQuery: function(query){ //search
			this.query = query;
            this.refresh();
		},
        refresh: function(){
			var me = this;
            if (me.query == null){
				me.query = new QueryDto();
				me.query.states = ['draft', 'in_transit'];
				//me.query.startDate = new Date().format('Y-m-d');
            }
            me.saleId = null;
           	SaleManager.findSales(me.query, function(data){
			    me.store.loadData(data);
			    me.view.collapseAllGroups();
		
			   // if (me.group)
				//  me.view.toggleGroup(me.view.getGroupId(me.group.id));
			    
		    });
		}
   });

   Ext.reg("salesgrid", avatar.salesPanel);

  //货运单编辑器
  avatar.carriageBuilder = Ext.extend(Ext.Panel, {
  	   saleId: null,
  	   idprefix: '',
  	   trackingNumber: '',
  	   isValid: function(showMessage){ 	   	 
  	   	 var b1 = Ext.getCmp(this.idprefix + 'carrier-selector').isValid(), 
  	   	     b2 = Ext.getCmp(this.idprefix + 'carriage-item-grid').getStore().getCount()>0;
  	   	     
  	   	if (!b2 && showMessage)
  	   	    alert('货运单至少应该增加一个产品。');
  	   	    
        return b1 & b2;  	   	     
  	   },
  	   clear : function(){
  	   	  this.carriage_item_ds.removeAll();
  	   },
  	   loadProductsInSale: function(){
  	   	    var me = this;
  	   	 	SaleManager.getSaleById(me.saleId, function(data){ 
			    for (var i = 0; i < data.items.length; i++) {		    	
       	  	      	me.product_in_sale_ds.insert(0,
	       	  	      	 new Ext.data.Record({
	       	  	      	    productId: data.items[i].product.id,
	       	  	      	    productName: data.items[i].product.name})
	       	  	    );   
			    }
			});
  	   },
  	   removeProductAvaiable: function(pid){
  	   	  var index = this.product_in_sale_ds.findExact('productId', pid); 
  	   	  this.product_in_sale_ds.removeAt(index);
  	   },
  	   addProductAvaiable: function(pid, pname){
  	   	  this.product_in_sale_ds.insert(0,  new Ext.data.Record({ productId: pid, productName: pname}));
  	   },
  	   getCarriage : function(){
  	   	  var carriage = new CarriageDto();
          //populate Carrage
   	      carriage.carrierId = Ext.getCmp(this.idprefix + 'carrier-selector').getValue();
	      carriage.locationIds = new Array();
	      carriage.productIds = new Array();
	      carriage.amounts = new Array();
          var returnedCmp = Ext.getCmp(this.idprefix + 'returned');
          if (returnedCmp.getValue()){
	         carriage.returned = true;
          }
   	      var store = Ext.getCmp(this.idprefix + 'carriage-item-grid').store;
   	      for (var i=0; i< store.getCount(); i++){
   	      	  var rec = store.getAt(i);
   	      	  carriage.locationIds[i] = rec.get('location');
   	      	  carriage.productIds[i] = rec.get('product');
   	      	  carriage.amounts[i] = rec.get('quantity');
   	      }
   	      return carriage;
  	   },
       initComponent: function() { 
           var me = this;
           var stock_ds = new Ext.data.SimpleStore({
				fields: [
				   'location',
				   'quantityForSale',
				   'quantity',
				   'transitQuantity'
				]
			}),
			location_ds = new Ext.data.JsonStore({
				fields: [ 'id', 'name' ]
			}),
			carrier_ds = new Ext.data.JsonStore({
                fields: [ 'id', 'name' ]
			});
			me.product_in_sale_ds = new Ext.data.SimpleStore({
				fields: [ 'productId', 'productName' ]
			});
			me.carriage_item_ds = new Ext.data.SimpleStore({
				fields: [
				   'location',
				   'product',
				   'quantity'
				]
			});
			
            me.loadProductsInSale();
            
			ProductManager.getAllLocation(function(data){ location_ds.loadData(data); });
			PartyManager.getAllActivePartyByRole('carrier', function(data){ carrier_ds.loadData(data); });
			
			var inventory_sm = new Ext.grid.RowSelectionModel({singleSelect:true}),
			    carriage_item_sm = new Ext.grid.RowSelectionModel({singleSelect:true});
			    
			carriage_item_sm.on('selectionchange', function(sm){	
		        var record = sm.getSelected();
		        var btn = Ext.getCmp(me.idprefix + 'remove-carriage-item');	        
		        btn.setDisabled(!record);

			});    
			    
			inventory_sm.on('selectionchange', function(sm){	
		        var record = sm.getSelected();
		        var btn = Ext.getCmp(me.idprefix + 'add-carriage-item-btn');
		        if (record && Ext.isNumber(record.get('transitQuantity')))
		           btn.setDisabled(false);
		        else   
		           btn.setDisabled(true);
			});
			
			var config = {
				border: false,
			    layout:'border',
			    height: 208,
			    items:[
			      //product source
			      { xtype : 'editorgrid',
				    region: 'center',
					store: stock_ds,
					columns: [ 
					   {header: '仓库位置', dataIndex : 'location', width: 75, renderer: function(val){
					      var index = location_ds.findExact('id', val);
					      return location_ds.getAt(index).get('name');
					   } },
					   {header: '可用数量', dataIndex : 'quantityForSale', width : 60},
					   {header: '最大数量', dataIndex : 'quantity', width : 60},
					   {header: '运送数量', dataIndex : 'transitQuantity', width: 60,
					     editor: {
							xtype: 'numberfield',
							allowDecimals: false
						}} 
					],
					sm: inventory_sm,				
					border: 1,
					enableHdMenu: false,
					//clicksToEdit:1,
					tbar: [
					 new Ext.ux.SelectBox({  				 	
                       listClass:'x-combo-list-small',
                       id: me.idprefix + 'carriage-product-selector',
                       displayField: 'productName',
                       valueField: 'productId',
                       store: me.product_in_sale_ds,
                       listeners: {
                       	  select : function(self, rec, index){
                       	  	 //refresh product inventory grid
                       	  	 ProductManager.getLocatedInventoriesByProductId(self.getValue(), function(data){
                       	  	      stock_ds.removeAll();
                       	  	      for (var i = 0; i < data.length; i++) {
                       	  	      	stock_ds.insert(0,
                       	  	      	 new Ext.data.Record({
                       	  	      	    location:data[i].location.id,
                       	  	      	    quantity:data[i].quantity,
                       	  	      	    quantityForSale: data[i].quantityForSale,
                       	  	      	    transitQuantity: ''
                       	  	      	    })
                       	  	      	  ); 
                       	  	      	
                       	  	      }
                       	  	 });
                       	  }
                       }
					}),
					{id: me.idprefix + 'add-carriage-item-btn', text:'加入货运单->', disabled: true, handler: 
					  function(){
					  	  var rec = inventory_sm.getSelected(),
					  	  amount = rec.get('transitQuantity'),
					  	  max = rec.get('quantity');
					  	  
					  	  if (amount > max){
					  	  	  alert('不能超出库存数量' + max );
					  	  	  return;
					  	  }
					  	  
					  	  me.carriage_item_ds.insert(0,
					  	    new Ext.data.Record({
					  	       location:rec.get('location'),  
					  	       product:Ext.getCmp(me.idprefix + 'carriage-product-selector').getValue(),
					  	       quantity:amount
					        })
					  	  )
					  	  
					  }
					}
					],					
				    listeners : {
				    	afteredit : function(o){
				    		inventory_sm.fireEvent('selectionchange', inventory_sm);
				    	}
				    }
	        	  },
	        	  //selection pool
	        	  { xtype: 'grid',
	        	    region: 'east',
	        	    id: me.idprefix + 'carriage-item-grid',
	        	    margins: '0 0 0 5',
	        	    sm: carriage_item_sm,
	        	    border: 1,
	        	    width: 260,
	        	    //frame: true,
	        	    enableHdMenu: false,
	        	    store: me.carriage_item_ds,
	        	    columns: [ 
	        	       new Ext.grid.RowNumberer(),
					   {header: '仓库位置', dataIndex : 'location', sortable:true, width: 75, renderer: function(val){
					      var index = location_ds.findExact('id', val);
					      return location_ds.getAt(index).get('name');
					   } },
					   {header: '产品', dataIndex : 'product', sortable:true, width : 90, renderer: function(val){
					      var index = me.product_in_sale_ds.findExact('productId', val);
					      return me.product_in_sale_ds.getAt(index).get('productName');
					   }},
					   {header: '数量', dataIndex : 'quantity', width : 58}
					],
					tbar: [
					   {id : me.idprefix + 'remove-carriage-item', iconCls:'remove', disabled: true, handler: function(){
					       me.carriage_item_ds.remove(carriage_item_sm.getSelected());					   	
					   }},
					   { iconCls:'print', handler : function(){ 
					     	var grid = Ext.getCmp(me.idprefix + 'carriage-item-grid');	
					     	var customerCmp = Ext.getCmp('sale-customer-name');
							if (me.isValid(true)){
								if (customerCmp){
									me.customer = new Customer();
									me.customer.name = Ext.getCmp('sale-customer-name').getValue();
            		   	            me.customer.freightPrice = Ext.getCmp('sale-customer-delivery-price').getValue();
            		   	            me.customer.phoneNumber = Ext.getCmp('sale-customer-phonenumber').getValue();
								}
								var fee = sumPlus(grid.getStore(), 'quantity') * me.customer.freightPrice;
								fee = Math.round(fee*100)/100;
								
								var tn = me.trackingNumber;
								
								if (tn == null || tn == ''){
								  dwr.engine.setAsync(false);
								  TrackingNumberGenerator.createSaleTrackingNumber(function(d){ tn = d; });
								  dwr.engine.setAsync(true);
								}
								
								var subtitle = 
								            '客户名称:<b>' + me.customer.name + '</b><br/>'
								            + '电话:' + me.customer.phoneNumber ;
								            
								           
								            
								var footer = '运输班组:' + Ext.getCmp(me.idprefix + 'carrier-selector').getRawValue() 
								    + ' 总数量:' + grid.store.sum('quantity') 
								    + ' 运输单价:' + (me.customer.freightPrice > 0 ? me.customer.freightPrice : '待定');
								if (me.customer.freightPrice > 0)   
								    footer += ' 总运费:' + fee;
								 printCarriageForm(grid, '<b>秦峰预制厂运输单 ' + tn + '</b>', subtitle, footer);
							}
							    	
					    } },				   
					   
					   '退板:', {xtype:'checkbox', id: me.idprefix + 'returned'},
					   '->', 
					   
					   '运输班组:',
					   new Ext.ux.SelectBox({  
	                       listClass:'x-combo-list-small',
	                       id: me.idprefix + 'carrier-selector',
	                       width: 75,
	                       store: carrier_ds,
	                       displayField: 'name',
	                       valueField: 'id',
	                       allowBlank: false
					   })
					]
	        	  }			    
			    ]
			};

            Ext.apply(this, config);
             //call parent
            avatar.carriageBuilder.superclass.initComponent.apply(this);
         }
  });
  
  Ext.reg("carriagebuilder", avatar.carriageBuilder);
  
  avatar.getDwrStore = function(managerAndMethod, fieldArray){
		return new Ext.data.Store({
                        proxy: new Ext.data.DWRProxy(eval(managerAndMethod),false),
                        reader:new Ext.data.DWRJsonReader({
			    		     totalProperty : "results",
						     root : "rows",                
			    	         id : "id"
					    },
					    fieldArray
				    )
                 });
	}
   
 //for report print
   function printGrid(grid, title, subtitle, footertext, copies){
		global_printer = new Ext.grid.XPrinter({
			copies: copies || 1,
			grid:grid,  // grid object 
			pathPrinter:'./js-lib/ext-ux-js/xtprinter/printer',  // relative to where the Printer folder resides  
			logoURL: false, // relative to the html files where it goes the base printing  
			pdfEnable: false,  // enables link PDF printing (only save as) 
			hasrowAction:false, 
			localeData:{
				Title: title,	
				subTitle: subtitle,	
				footerText: footertext, 
				pageNo:'页 # ',	//page label
				printText:'打印',  //print document action label 
				closeText:'关闭',  //close window action label 
				pdfText:'PDF'},
			useCustom:{  // in this case you leave null values as we dont use a custom store and TPL
				custom:false,
				customStore:null, 
				columns:[], 
				alignCols:[],
				pageToolbar:null, 
				useIt: false, 
				showIt: false, 
				location: 'bbar'
			},
			showdate:true,// show print date 
			showdateFormat:'Y-m-d H:i', 
			showFooter:true,  // if the footer is shown on the pinting html 
			styles:'default' // wich style youre gonna use 
		}); 

		global_printer.prepare(); // prepare the document 
  }

  function printAccountingReport(grid, title, subtitle, footer){
      printGrid(grid, title, subtitle, footer);
  }
  
  function printWarehousingForm(grid, title, subtitle){
	  printGrid(grid, title, subtitle, '');
  }
  
  function printCarriageForm(grid, title, subtitle, footer){
  	  printGrid(grid, title, subtitle, footer);
  }
  
  function sumPlus (store, property){
        var rs = store.data.items, v = 0,
        start = 0,
        end = rs.length-1;

        for(var i = start; i <= end; i++){
        	var q = parseInt(rs[i].data[property]);
        	if (q > 0)
              v += q;
        }
        return v;
    }